package com.example.service.impl;

import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.pojo.vo.LoginUser;
import com.example.service.LoginService;
import com.example.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result login(User user) {
        // authenticationManager 认证
        UsernamePasswordAuthenticationToken uToken = new UsernamePasswordAuthenticationToken(user.getUsername(),
                user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(uToken);
        // 获取用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        // 生成token
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        String token = JwtUtils.generateToken(map);
        // 存入redis
        redisTemplate.opsForValue().set("login:" + userId, loginUser);
        return Result.success(token);
    }

    @Override
    public Result logout() {
        // 从SecurityContextHolder中获取用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Integer userId = loginUser.getUser().getId();
        String redisKey = "login:" + userId;
        redisTemplate.delete(redisKey);
        return Result.success();
    }
}
